package cn.sinokj.party.chineseFourParty.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.base.BaseActivity;
import cn.sinokj.party.chineseFourParty.adapter.NewsAdapter;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.bean.IndexImage;
import cn.sinokj.party.chineseFourParty.bean.NewsInfo;
import cn.sinokj.party.chineseFourParty.service.HttpConstants;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;

/**
 * Created by l on 2017/10/30.
 */

public class SearchActivity extends BaseActivity {
    @BindView(R.id.rl_search_history)
    public RecyclerView rlSearchHistory;
    @BindView(R.id.edit_search)
    public EditText editSearch;
    @BindView(R.id.btn_search)
    public Button btnSearch;
    @BindView(R.id.rl_search_news)
    public RecyclerView rlSearchNews;
    @BindView(R.id.ll_rel)
    public LinearLayout llRel;


    private List<String> historyList;
    private SearchHistoryAdapter histortAdapter;
    private String key;
    private InputMethodManager imm;
    public static final int SEARCH_DATA = 134;
    private String vcPlatform = "e党建";
    private int nPageNo = 1;
    private int nPageSize = 100;
    public static final int TO_CHANGE_READ_STATUS = 3;
    private IndexImage indexImage;
    private NewsAdapter newsAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initTitle();
        initHistory();

        editSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    rlSearchHistory.setVisibility(View.VISIBLE);
                    rlSearchNews.setVisibility(View.GONE);
                } else {
                    rlSearchHistory.setVisibility(View.GONE);
                    rlSearchNews.setVisibility(View.VISIBLE);
                }
            }
        });
        llRel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputWindow(SearchActivity.this);
            }
        });
    }

    private void initTitle() {
        ImmersionBar.with(this).statusBarColor(R.color.white)
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.black).init();

        imm = (InputMethodManager) editSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @OnClick({R.id.btn_search})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {

            case R.id.btn_search:
                hideInputWindow(SearchActivity.this);
                searchData();
                if (histortAdapter == null) {
                    createHisAdapter();
                } else {
                    histortAdapter.setNewData(historyList);
                }
                break;
        }

    }

    private void createHisAdapter() {
        histortAdapter = new SearchHistoryAdapter(historyList);
        rlSearchHistory.setLayoutManager(new LinearLayoutManager(this));
        rlSearchHistory.setAdapter(histortAdapter);
        histortAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                key = histortAdapter.getData().get(position);
                editSearch.setText(key);
                hideInputWindow(SearchActivity.this);
                searchData();
                histortAdapter.setNewData(historyList);
            }
        });
    }

    private void initHistory() {
        historyList = preferencesUtil.getList("historyList", String.class);
        if (historyList == null) {
            historyList = new ArrayList<>();
        }
        if (historyList.size() != 0) {
            createHisAdapter();
        }
    }


    private void searchData() {
        key = editSearch.getText().toString().trim();
        if (TextUtils.isEmpty(key)) {
            Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
            return;
        }
        historyList.add(0, key);
        if (historyList.size() > 10) {
            historyList = historyList.subList(0, 9);
        }
        DialogShow.showRoundProcessDialog(this);
        new Thread(new LoadDataThread(SEARCH_DATA, key)).start();
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case SEARCH_DATA:
                return HttpDataService.searchNews(nPageNo, nPageSize, (String) obj, App.nCommitteeId);
            case TO_CHANGE_READ_STATUS:
                return HttpDataService.getSingleReadStatus(String.valueOf(indexImage.nId));
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        super.httpHandlerResultData(msg, jsonObject);
        switch (msg.what) {
            case TO_CHANGE_READ_STATUS:
                indexImage.nStatus = (jsonObject.optInt(HttpConstants.RESULT));
                indexImage.nclick = Integer.valueOf(jsonObject.optString("nClick"));
                newsAdapter.notifyDataSetChanged();
                break;
            case SEARCH_DATA:
                String json = jsonObject.toString();
                Gson gson = new Gson();
                NewsInfo searchInfo = gson.fromJson(json, NewsInfo.class);
                initView(searchInfo.objects);
                break;
        }
    }

    private void initView(List<IndexImage> objects) {
        if (newsAdapter == null) {
            newsAdapter = new NewsAdapter(objects);
            rlSearchNews.setLayoutManager(new LinearLayoutManager(this));
            rlSearchNews.setAdapter(newsAdapter);
        } else {
            newsAdapter.setNewData(objects);
            newsAdapter.notifyDataSetChanged();
        }

        if (newsAdapter.getData().isEmpty()) {
            View emptyView = getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup)
                    rlSearchNews.getParent(), false);
            newsAdapter.setEmptyView(emptyView);
        }

        newsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<IndexImage> data = newsAdapter.getData();
                indexImage = data.get(position);
                Intent intent = new Intent(SearchActivity.this, IndexImageWebActivity.class);
                intent.putExtra("url", indexImage.url);
                intent.putExtra("icon", indexImage.vcPath);
                intent.putExtra("topTitle", indexImage.vcType);
                //intent.putExtra("title", functionType);
                intent.putExtra("nShared", indexImage.nShared);
                intent.putExtra("describe", indexImage.vcDescribe);
                startActivityForResult(intent, TO_CHANGE_READ_STATUS);
            }
        });
    }


    @Override
    protected void onStop() {
        super.onStop();
        preferencesUtil.putList("historyList", historyList);

    }


    public void hideInputWindow(Activity context) {
        if (context == null) {
            return;
        }
        final View v = getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        editSearch.clearFocus();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (App.loginStatus && resultCode == Activity.RESULT_OK && requestCode == TO_CHANGE_READ_STATUS) {
            new Thread(new LoadDataThread(TO_CHANGE_READ_STATUS)).start();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    class SearchHistoryAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public SearchHistoryAdapter(List<String> data) {
            super(R.layout.item_seachhistory, data);
        }

        @Override
        protected void convert(final BaseViewHolder baseViewHolder, String s) {
            baseViewHolder.setText(R.id.tv_his, s);
            baseViewHolder.setOnClickListener(R.id.tv_delete, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    historyList.remove(baseViewHolder.getLayoutPosition());
                    setNewData(historyList);
                }
            });
        }
    }
}
